package com.qingzhuge.sys.service.impl;

import com.google.gson.Gson;
import com.qingzhuge.interfaces.IPersistable;
import com.qingzhuge.service.BasePkLongServiceImpl;
import com.qingzhuge.sys.dao.SysConfigDao;
import com.qingzhuge.sys.entity.SysConfig;
import com.qingzhuge.sys.entity.SysSiteConfig;
import com.qingzhuge.sys.service.ISysConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static com.qingzhuge.sys.entity.SysSiteConfig.SYS_SITE_CONFIG_KEY;
import static com.qingzhuge.sys.service.impl.SysConfigServiceImpl.CACHE_NAME;


/**
 * @author : zero.xiao
 * @description :
 * @date :2018/9/19 0019 下午 17:51
 * @modified :
 * @since : 1.0.0
 */
@Service
@CacheConfig(cacheNames = CACHE_NAME)
public class SysConfigServiceImpl extends BasePkLongServiceImpl<SysConfigDao, SysConfig> implements ISysConfigService {

    static final String CACHE_NAME = "sysConfigService";

    @Override
    @Transactional(rollbackFor = java.lang.Exception.class)
    public SysConfig save(SysConfig config) {
        if (null != config && StringUtils.isNotBlank(config.getKey())) {
            saveCache(config.getKey(), super.save(config));
        }
        return config;
    }

    @Override
    public SysConfig getValue(String key) {
        if (null == key) {
            return null;
        }
        SysConfig entity = getCache(key);
        if (entity == null) {
            entity = baseDao.queryByKey(key);
            saveCache(key, entity);
        }
        return entity;
    }

    @Override
    public <T extends IPersistable> T getConfigObject(String key, Class<T> clazz) {
        SysConfig config = getValue(key);
        if (null != config && StringUtils.isNotBlank(config.getValue())) {
            T t = new Gson().fromJson(config.getValue(), clazz);
            try {
                t.setId(config.getId());
            } catch (Exception e) {
                t.setId(config.getId().toString());
            }
            return t;
        } else {
            return null;
        }
    }

    @Override
    public SysSiteConfig getSiteConfig() {
        return this.getConfigObject(SYS_SITE_CONFIG_KEY, SysSiteConfig.class);
    }
}
